#nullable enable

namespace Application.Service.Auth;

/// <summary>
/// 会话管理服务
/// <para>功能：提供会话管理的Web API接口</para>
/// <list type="bullet">
/// <item><description>提供活跃会话查询接口</description></item>
/// <item><description>提供强制注销用户接口</description></item>
/// <item><description>提供用户登录状态检查接口</description></item>
/// <item><description>封装会话管理功能为Web服务</description></item>
/// </list>
/// </summary>
[ApiDescriptionSettings(SplitCamelCase = false)]
[Route("api/session")]
public class SessionService : IDynamicApiController
{
    private readonly SessionManagerService _sessionManager;
    private readonly AuthService _authService;

    public SessionService(SessionManagerService sessionManager, AuthService authService)
    {
        _sessionManager = sessionManager;
        _authService = authService;
    }

    /// <summary>
    /// 查询当前系统中所有活跃的会话信息
    /// </summary>
    /// <returns>返回活跃会话数量和用户ID列表</returns>
    [HttpGet]
    public object GetActiveSessions()
    {
        var activeUserIds = _sessionManager.GetActiveUserIds();
        var sessionCount = _sessionManager.GetActiveSessionCount();

        return new
        {
            ActiveSessionCount = sessionCount,
            ActiveUserIds = activeUserIds
        };
    }

    /// <summary>
    /// 通过Web API强制终止指定用户的会话(强制注销指定用户)
    /// </summary>
    /// <param name="userId">用户ID</param>
    /// <returns>返回强制注销操作的结果和状态信息</returns>
    [HttpPost("logout/{userId}")]
    public object Logout(int userId)
    {
        var result = _authService.ForceLogout(userId);

        return new
        {
            Success = result,
            Message = result ? "强制注销成功" : "强制注销失败，用户可能未登录"
        };
    }

    /// <summary>
    /// 通过Web API查询指定用户的登录状态(检查用户是否已登录)
    /// </summary>
    /// <param name="userId">用户ID</param>
    /// <returns>返回用户登录状态和会话信息</returns>
    [HttpGet("status/{userId}")]
    public object IsUserLoggedIn(int userId)
    {
        var isLoggedIn = _sessionManager.IsUserLoggedIn(userId);

        return new
        {
            UserId = userId,
            IsLoggedIn = isLoggedIn,
            SessionId = isLoggedIn ? _sessionManager.GetUserSessionId(userId) : null
        };
    }
}
